const API = {
  base: window.location.origin, // 动态获取当前页面的域名和端口
  headers() {
    const token = localStorage.getItem('sky_admin_token');
    const h = { 'Content-Type': 'application/json' };
    // 后端约定管理员token头名称为 token（见 application.yml）
    if (token) h['token'] = token;
    return h;
  },
  async get(path, params = {}) {
    const url = new URL(path, this.base);
    Object.entries(params).forEach(([k, v]) => {
      if (v !== null && v !== undefined && v !== '') url.searchParams.set(k, v);
    });
    const res = await fetch(url.toString(), { headers: this.headers() });
    if (!res.ok) {
      const text = await res.text();
      throw new Error(`GET ${path} ${res.status}: ${text}`);
    }
    const ct = res.headers.get('content-type') || '';
    if (!ct.includes('application/json')) {
      const text = await res.text();
      try { return JSON.parse(text); } catch { return { raw: text }; }
    }
    return res.json();
  },
  async send(method, path, body) {
    const res = await fetch(new URL(path, this.base).toString(), {
      method,
      headers: this.headers(),
      body: body ? JSON.stringify(body) : undefined,
    });
    return res.json();
  },
  async put(path, body) {
    return this.send('PUT', path, body);
  },
  async upload(path, file) {
    const form = new FormData();
    form.append('file', file);
    const token = localStorage.getItem('sky_admin_token');
    const headers = token ? { token } : undefined;
    const res = await fetch(new URL(path, this.base).toString(), { method: 'POST', headers, body: form });
    return res.json();
  },
};

// 渲染用户统计图表（双线图）
function renderUserChart(containerId, labels = [], newUserValues = [], totalUserValues = []) {
  const container = document.getElementById(containerId);
  if (!container) return;
  
  container.innerHTML = '';
  const canvas = document.createElement('canvas');
  const cw = container.clientWidth || 600;
  const ch = container.clientHeight || 280;
  canvas.width = cw;
  canvas.height = ch;
  container.appendChild(canvas);
  const ctx = canvas.getContext('2d');

  const margin = { left: 48, right: 12, top: 16, bottom: 48 };
  const W = cw - margin.left - margin.right;
  const H = ch - margin.top - margin.bottom;
  ctx.clearRect(0, 0, cw, ch);

  ctx.fillStyle = '#ffffff';
  ctx.fillRect(0, 0, cw, ch);

  // 坐标轴
  ctx.strokeStyle = '#e5e7eb';
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(margin.left, margin.top);
  ctx.lineTo(margin.left, margin.top + H);
  ctx.lineTo(margin.left + W, margin.top + H);
  ctx.stroke();

  if (!newUserValues.length && !totalUserValues.length) return;

  const allValues = [...newUserValues, ...totalUserValues];
  const minVal = Math.min(...allValues);
  const maxVal = Math.max(...allValues);
  const span = maxVal - minVal || 1;
  const yScale = H / span;
  const xStep = labels.length > 1 ? W / (labels.length - 1) : 0;

  // 网格线
  const gridLines = 4;
  ctx.strokeStyle = '#f3f4f6';
  for (let i = 1; i <= gridLines; i++) {
    const y = margin.top + (H * i) / gridLines;
    ctx.beginPath();
    ctx.moveTo(margin.left, y);
    ctx.lineTo(margin.left + W, y);
    ctx.stroke();
  }

  // 绘制新增用户折线
  if (newUserValues.length) {
    ctx.strokeStyle = '#3b82f6';
    ctx.lineWidth = 2;
    ctx.beginPath();
    newUserValues.forEach((v, i) => {
      const x = margin.left + xStep * i;
      const y = margin.top + H - (v - minVal) * yScale;
      if (i === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    });
    ctx.stroke();

    ctx.fillStyle = '#3b82f6';
    newUserValues.forEach((v, i) => {
      const x = margin.left + xStep * i;
      const y = margin.top + H - (v - minVal) * yScale;
      ctx.beginPath();
      ctx.arc(x, y, 3, 0, Math.PI * 2);
      ctx.fill();
    });
  }

  // 绘制总用户折线
  if (totalUserValues.length) {
    ctx.strokeStyle = '#10b981';
    ctx.lineWidth = 2;
    ctx.beginPath();
    totalUserValues.forEach((v, i) => {
      const x = margin.left + xStep * i;
      const y = margin.top + H - (v - minVal) * yScale;
      if (i === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    });
    ctx.stroke();

    ctx.fillStyle = '#10b981';
    totalUserValues.forEach((v, i) => {
      const x = margin.left + xStep * i;
      const y = margin.top + H - (v - minVal) * yScale;
      ctx.beginPath();
      ctx.arc(x, y, 3, 0, Math.PI * 2);
      ctx.fill();
    });
  }

  // Y轴刻度
  ctx.fillStyle = '#6b7280';
  ctx.font = '12px system-ui, Arial';
  const tickCount = 4;
  for (let i = 0; i <= tickCount; i++) {
    const val = minVal + (span * i) / tickCount;
    const y = margin.top + H - (val - minVal) * yScale;
    ctx.fillText(val.toFixed(0), 8, y + 4);
  }

  // X轴标签
  const maxLabels = 10;
  const step = Math.ceil(labels.length / maxLabels);
  labels.forEach((lab, i) => {
    if (i % step !== 0 && i !== labels.length - 1) return;
    const x = margin.left + xStep * i;
    const y = margin.top + H + 16;
    const text = String(lab).slice(5);
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(-Math.PI / 8);
    ctx.fillText(text, -12, 0);
    ctx.restore();
  });

  // 图例
  ctx.fillStyle = '#3b82f6';
  ctx.fillRect(margin.left, 8, 12, 8);
  ctx.fillStyle = '#6b7280';
  ctx.fillText('新增用户', margin.left + 16, 16);
  
  ctx.fillStyle = '#10b981';
  ctx.fillRect(margin.left + 80, 8, 12, 8);
  ctx.fillStyle = '#6b7280';
  ctx.fillText('总用户', margin.left + 96, 16);
}

// 渲染订单统计图表（双线图）
function renderOrderChart(containerId, labels = [], validOrderValues = [], totalOrderValues = []) {
  const container = document.getElementById(containerId);
  if (!container) return;
  
  container.innerHTML = '';
  const canvas = document.createElement('canvas');
  const cw = container.clientWidth || 600;
  const ch = container.clientHeight || 280;
  canvas.width = cw;
  canvas.height = ch;
  container.appendChild(canvas);
  const ctx = canvas.getContext('2d');

  const margin = { left: 48, right: 12, top: 16, bottom: 48 };
  const W = cw - margin.left - margin.right;
  const H = ch - margin.top - margin.bottom;
  ctx.clearRect(0, 0, cw, ch);

  ctx.fillStyle = '#ffffff';
  ctx.fillRect(0, 0, cw, ch);

  // 坐标轴
  ctx.strokeStyle = '#e5e7eb';
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(margin.left, margin.top);
  ctx.lineTo(margin.left, margin.top + H);
  ctx.lineTo(margin.left + W, margin.top + H);
  ctx.stroke();

  if (!validOrderValues.length && !totalOrderValues.length) return;

  const allValues = [...validOrderValues, ...totalOrderValues];
  const minVal = Math.min(...allValues);
  const maxVal = Math.max(...allValues);
  const span = maxVal - minVal || 1;
  const yScale = H / span;
  const xStep = labels.length > 1 ? W / (labels.length - 1) : 0;

  // 网格线
  const gridLines = 4;
  ctx.strokeStyle = '#f3f4f6';
  for (let i = 1; i <= gridLines; i++) {
    const y = margin.top + (H * i) / gridLines;
    ctx.beginPath();
    ctx.moveTo(margin.left, y);
    ctx.lineTo(margin.left + W, y);
    ctx.stroke();
  }

  // 绘制有效订单折线
  if (validOrderValues.length) {
    ctx.strokeStyle = '#ef4444';
    ctx.lineWidth = 2;
    ctx.beginPath();
    validOrderValues.forEach((v, i) => {
      const x = margin.left + xStep * i;
      const y = margin.top + H - (v - minVal) * yScale;
      if (i === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    });
    ctx.stroke();

    ctx.fillStyle = '#ef4444';
    validOrderValues.forEach((v, i) => {
      const x = margin.left + xStep * i;
      const y = margin.top + H - (v - minVal) * yScale;
      ctx.beginPath();
      ctx.arc(x, y, 3, 0, Math.PI * 2);
      ctx.fill();
    });
  }

  // 绘制总订单折线
  if (totalOrderValues.length) {
    ctx.strokeStyle = '#8b5cf6';
    ctx.lineWidth = 2;
    ctx.beginPath();
    totalOrderValues.forEach((v, i) => {
      const x = margin.left + xStep * i;
      const y = margin.top + H - (v - minVal) * yScale;
      if (i === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    });
    ctx.stroke();

    ctx.fillStyle = '#8b5cf6';
    totalOrderValues.forEach((v, i) => {
      const x = margin.left + xStep * i;
      const y = margin.top + H - (v - minVal) * yScale;
      ctx.beginPath();
      ctx.arc(x, y, 3, 0, Math.PI * 2);
      ctx.fill();
    });
  }

  // Y轴刻度
  ctx.fillStyle = '#6b7280';
  ctx.font = '12px system-ui, Arial';
  const tickCount = 4;
  for (let i = 0; i <= tickCount; i++) {
    const val = minVal + (span * i) / tickCount;
    const y = margin.top + H - (val - minVal) * yScale;
    ctx.fillText(val.toFixed(0), 8, y + 4);
  }

  // X轴标签
  const maxLabels = 10;
  const step = Math.ceil(labels.length / maxLabels);
  labels.forEach((lab, i) => {
    if (i % step !== 0 && i !== labels.length - 1) return;
    const x = margin.left + xStep * i;
    const y = margin.top + H + 16;
    const text = String(lab).slice(5);
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(-Math.PI / 8);
    ctx.fillText(text, -12, 0);
    ctx.restore();
  });

  // 图例
  ctx.fillStyle = '#ef4444';
  ctx.fillRect(margin.left, 8, 12, 8);
  ctx.fillStyle = '#6b7280';
  ctx.fillText('有效订单', margin.left + 16, 16);
  
  ctx.fillStyle = '#8b5cf6';
  ctx.fillRect(margin.left + 80, 8, 12, 8);
  ctx.fillStyle = '#6b7280';
  ctx.fillText('总订单', margin.left + 96, 16);
}

// 渲染销量TOP10图表（柱状图）
function renderTop10Chart(containerId, dishNames = [], salesValues = []) {
  const container = document.getElementById(containerId);
  if (!container) return;
  
  container.innerHTML = '';
  const canvas = document.createElement('canvas');
  const cw = container.clientWidth || 600;
  const ch = container.clientHeight || 280;
  canvas.width = cw;
  canvas.height = ch;
  container.appendChild(canvas);
  const ctx = canvas.getContext('2d');

  const margin = { left: 48, right: 12, top: 16, bottom: 80 };
  const W = cw - margin.left - margin.right;
  const H = ch - margin.top - margin.bottom;
  ctx.clearRect(0, 0, cw, ch);

  ctx.fillStyle = '#ffffff';
  ctx.fillRect(0, 0, cw, ch);

  // 坐标轴
  ctx.strokeStyle = '#e5e7eb';
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(margin.left, margin.top);
  ctx.lineTo(margin.left, margin.top + H);
  ctx.lineTo(margin.left + W, margin.top + H);
  ctx.stroke();

  if (!salesValues.length || !dishNames.length) return;

  const maxVal = Math.max(...salesValues);
  const yScale = maxVal > 0 ? H / maxVal : 1;
  const barWidth = W / dishNames.length * 0.8;
  const barSpacing = W / dishNames.length * 0.2;

  // 网格线
  const gridLines = 4;
  ctx.strokeStyle = '#f3f4f6';
  for (let i = 1; i <= gridLines; i++) {
    const y = margin.top + (H * i) / gridLines;
    ctx.beginPath();
    ctx.moveTo(margin.left, y);
    ctx.lineTo(margin.left + W, y);
    ctx.stroke();
  }

  // 绘制柱状图
  ctx.fillStyle = '#f59e0b';
  salesValues.forEach((value, i) => {
    const x = margin.left + (W / dishNames.length) * i + barSpacing / 2;
    const barHeight = value * yScale;
    const y = margin.top + H - barHeight;
    
    ctx.fillRect(x, y, barWidth, barHeight);
    
    // 在柱子上方显示数值
    ctx.fillStyle = '#6b7280';
    ctx.font = '12px system-ui, Arial';
    ctx.textAlign = 'center';
    ctx.fillText(value.toString(), x + barWidth / 2, y - 4);
    ctx.fillStyle = '#f59e0b';
  });

  // Y轴刻度
  ctx.fillStyle = '#6b7280';
  ctx.font = '12px system-ui, Arial';
  ctx.textAlign = 'left';
  const tickCount = 4;
  for (let i = 0; i <= tickCount; i++) {
    const val = (maxVal * i) / tickCount;
    const y = margin.top + H - (val * yScale);
    ctx.fillText(val.toFixed(0), 8, y + 4);
  }

  // X轴标签（菜品名称）
  ctx.fillStyle = '#6b7280';
  ctx.font = '10px system-ui, Arial';
  ctx.textAlign = 'center';
  dishNames.forEach((name, i) => {
    const x = margin.left + (W / dishNames.length) * i + (W / dishNames.length) / 2;
    const y = margin.top + H + 16;
    
    // 如果名称太长，截断显示
    const displayName = name.length > 6 ? name.substring(0, 6) + '...' : name;
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(-Math.PI / 6);
    ctx.fillText(displayName, 0, 0);
    ctx.restore();
  });
}

function $(sel) { return document.querySelector(sel); }
function show(id) {
  document.querySelectorAll('.view').forEach(v => v.classList.add('hidden'));
  document.getElementById(id).classList.remove('hidden');
}
function updateAuthStatus() {
  const token = localStorage.getItem('sky_admin_token');
  $('#auth-status').textContent = token ? '已登录' : '未登录';
  
  // 控制退出登录按钮的显示
  const logoutBtn = $('#logout-btn');
  if (logoutBtn) {
    logoutBtn.style.display = token ? 'inline-block' : 'none';
  }
}

// 轻量级折线图渲染，无第三方依赖
function renderLineChart(containerId, labels = [], values = []) {
  const container = document.getElementById(containerId);
  if (!container) return;
  // 清空并创建画布
  container.innerHTML = '';
  const canvas = document.createElement('canvas');
  // 使用容器尺寸；若宽高为0则给默认值
  const cw = container.clientWidth || 600;
  const ch = container.clientHeight || 280;
  canvas.width = cw;
  canvas.height = ch;
  container.appendChild(canvas);
  const ctx = canvas.getContext('2d');

  const margin = { left: 48, right: 12, top: 16, bottom: 48 };
  const W = cw - margin.left - margin.right;
  const H = ch - margin.top - margin.bottom;
  ctx.clearRect(0, 0, cw, ch);

  // 背景
  ctx.fillStyle = '#ffffff';
  ctx.fillRect(0, 0, cw, ch);

  // 坐标轴
  ctx.strokeStyle = '#e5e7eb';
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(margin.left, margin.top);
  ctx.lineTo(margin.left, margin.top + H);
  ctx.lineTo(margin.left + W, margin.top + H);
  ctx.stroke();

  if (!values.length || !labels.length) return;

  const minVal = Math.min(...values);
  const maxVal = Math.max(...values);
  const span = maxVal - minVal || 1;
  const yScale = H / span;
  const xStep = values.length > 1 ? W / (values.length - 1) : 0;

  // 网格线
  const gridLines = 4;
  ctx.strokeStyle = '#f3f4f6';
  for (let i = 1; i <= gridLines; i++) {
    const y = margin.top + (H * i) / gridLines;
    ctx.beginPath();
    ctx.moveTo(margin.left, y);
    ctx.lineTo(margin.left + W, y);
    ctx.stroke();
  }

  // 折线
  ctx.strokeStyle = '#f59e0b';
  ctx.lineWidth = 2;
  ctx.beginPath();
  values.forEach((v, i) => {
    const x = margin.left + xStep * i;
    const y = margin.top + H - (v - minVal) * yScale;
    if (i === 0) ctx.moveTo(x, y);
    else ctx.lineTo(x, y);
  });
  ctx.stroke();

  // 数据点
  ctx.fillStyle = '#f59e0b';
  values.forEach((v, i) => {
    const x = margin.left + xStep * i;
    const y = margin.top + H - (v - minVal) * yScale;
    ctx.beginPath();
    ctx.arc(x, y, 3, 0, Math.PI * 2);
    ctx.fill();
  });

  // Y轴刻度
  ctx.fillStyle = '#6b7280';
  ctx.font = '12px system-ui, Arial';
  const tickCount = 4;
  for (let i = 0; i <= tickCount; i++) {
    const val = minVal + (span * i) / tickCount;
    const y = margin.top + H - (val - minVal) * yScale;
    ctx.fillText(val.toFixed(0), 8, y + 4);
  }

  // X轴标签（等距，最多显示10个）
  const maxLabels = 10;
  const step = Math.ceil(labels.length / maxLabels);
  labels.forEach((lab, i) => {
    if (i % step !== 0 && i !== labels.length - 1) return;
    const x = margin.left + xStep * i;
    const y = margin.top + H + 16;
    const text = String(lab).slice(5); // 只显示 MM-DD 简洁
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(-Math.PI / 8);
    ctx.fillText(text, -12, 0);
    ctx.restore();
  });
}

function showMainUI() {
  const loginPage = document.getElementById('login-page');
  const headerEl = document.querySelector('header');
  const mainEl = document.querySelector('main');
  loginPage.classList.add('hidden');
  headerEl.classList.remove('hidden');
  mainEl.classList.remove('hidden');
}

document.addEventListener('DOMContentLoaded', () => {
  // 未登录仅显示登录分屏，隐藏主框架
  const hasToken = !!localStorage.getItem('sky_admin_token');
  const loginPage = document.getElementById('login-page');
  const headerEl = document.querySelector('header');
  const mainEl = document.querySelector('main');
  const asideEl = document.querySelector('aside.sidebar');
  if (!hasToken) {
    loginPage.classList.remove('hidden');
    headerEl.classList.add('hidden');
    mainEl.classList.add('hidden');
    asideEl && asideEl.classList.add('hidden');
  } else {
    showMainUI();
  }
  // 导航切换
  document.querySelectorAll('.sidebar .nav-item').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.sidebar .nav-item').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      show(`view-${btn.dataset.view}`);
      // 侧栏切换后自动加载对应模块第一页
      const view = btn.dataset.view;
      const DEFAULT = { page: 1, pageSize: 10 };
      if (view === 'category') loadCategory(DEFAULT);
      else if (view === 'dish') loadDish(DEFAULT);
      else if (view === 'setmeal') loadSetmeal(DEFAULT);
      else if (view === 'order') loadOrders(DEFAULT);
      else if (view === 'employee' && typeof loadEmployees === 'function') {
        try { loadEmployees(DEFAULT); } catch {}
      }
    });
  });

  updateAuthStatus();

  // 已登录则默认展示“员工管理”视图并加载列表
  if (localStorage.getItem('sky_admin_token')) {
    show('view-employee');
    if (typeof loadEmployees === 'function') {
      try { loadEmployees({ page: 1, pageSize: 10 }); } catch (e) {}
    }
  }

  // 登录
  $('#login-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(e.target).entries());
    const res = await API.send('POST', '/admin/employee/login', data);
    // 可选：开发调试输出
    const debugOut = document.getElementById('login-result');
    if (debugOut) debugOut.textContent = JSON.stringify(res, null, 2);
    const success = res && (res.code === 1 || res.success) && res.data;
    if (success) {
      const token = res.data.token;
      if (token) localStorage.setItem('sky_admin_token', token);
      updateAuthStatus();
      showMainUI();
      asideEl && asideEl.classList.remove('hidden');
      // 默认激活侧栏“员工管理”并展示
      const empBtn = document.querySelector('.sidebar .nav-item[data-view="employee"]');
      empBtn && empBtn.classList.add('active');
      show('view-employee');
      if (typeof loadEmployees === 'function') {
        try { loadEmployees({ page: 1, pageSize: 10 }); } catch (e) {}
      }
    } else {
      alert((res && res.msg) ? `登录失败：${res.msg}` : '登录失败，请检查账号或网络。');
    }
  });

  // 工作台
  $('#btn-businessData').addEventListener('click', async () => {
    try {
      const res = await API.get('/admin/workspace/businessData');
      const tbody = $('#business-data-tbody');
      if (res && res.data) {
        const data = res.data;
        tbody.innerHTML = `
          <tr>
            <td>¥${data.turnover || '0.00'}</td>
            <td>${data.validOrderCount || 0}</td>
            <td>${data.orderCompletionRate || '0%'}</td>
            <td>¥${data.averageOrderAmount || '0.00'}</td>
            <td>${data.newUsers || 0}</td>
          </tr>
        `;
      } else {
        tbody.innerHTML = '<tr><td colspan="5" class="loading">暂无数据</td></tr>';
      }
    } catch (error) {
      $('#business-data-tbody').innerHTML = '<tr><td colspan="5" class="loading">数据加载失败</td></tr>';
    }
  });
  
  $('#btn-overviewOrders').addEventListener('click', async () => {
    try {
      const res = await API.get('/admin/workspace/overviewOrders');
      const tbody = $('#orders-overview-tbody');
      if (res && res.data && Array.isArray(res.data)) {
        if (res.data.length > 0) {
          tbody.innerHTML = res.data.slice(0, 5).map(order => `
            <tr>
              <td>${order.number || '-'}</td>
              <td><span class="${getOrderStatusClass(order.status)}">${getOrderStatusText(order.status)}</span></td>
              <td>${order.userName || '-'}</td>
              <td>¥${order.amount || '0.00'}</td>
              <td>${order.orderTime ? new Date(order.orderTime).toLocaleString() : '-'}</td>
            </tr>
          `).join('');
        } else {
          tbody.innerHTML = '<tr><td colspan="5" class="loading">暂无订单数据</td></tr>';
        }
      } else {
        tbody.innerHTML = '<tr><td colspan="5" class="loading">暂无数据</td></tr>';
      }
    } catch (error) {
      $('#orders-overview-tbody').innerHTML = '<tr><td colspan="5" class="loading">数据加载失败</td></tr>';
    }
  });

  // 店铺
  $('#btn-getShopStatus').addEventListener('click', async () => {
    const res = await API.get('/admin/shop/status');
    $('#shop-result').textContent = JSON.stringify(res, null, 2);
  });
  $('#btn-openShop').addEventListener('click', async () => {
    const res = await API.send('PUT', '/admin/shop/1');
    $('#shop-result').textContent = JSON.stringify(res, null, 2);
  });
  $('#btn-closeShop').addEventListener('click', async () => {
    const res = await API.send('PUT', '/admin/shop/0');
    $('#shop-result').textContent = JSON.stringify(res, null, 2);
  });

  // 分类分页
  $('#category-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const params = Object.fromEntries(new FormData(e.target).entries());
    await loadCategory(params);
  });
  async function loadCategory(params = { page: 1, pageSize: 10 }) {
    const res = await API.get('/admin/category/page', params);
    renderPagedTable('#category-table', res, params, (p) => loadCategory({ ...params, page: p }));
  }

  // 菜品分页
  $('#dish-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const params = Object.fromEntries(new FormData(e.target).entries());
    await loadDish(params);
  });
  async function loadDish(params = { page: 1, pageSize: 10 }) {
    const res = await API.get('/admin/dish/page', params);
    renderPagedTable('#dish-table', res, params, (p) => loadDish({ ...params, page: p }));
  }

  // 修改菜品功能
  window.modifyDish = async function(dishId) {
    try {
      // 根据ID查询菜品详细信息
      const dishRes = await API.get(`/admin/dish/${dishId}`);
      if (dishRes.code === 1 && dishRes.data) {
        // 显示修改表单弹窗
        showDishModifyModal(dishRes.data);
      } else {
        alert('获取菜品信息失败：' + (dishRes.msg || '未知错误'));
      }
    } catch (error) {
      console.error('查询菜品详情失败:', error);
      alert('查询菜品详情失败，请稍后重试');
    }
  };

  // 显示菜品修改弹窗
  async function showDishModifyModal(dishData) {
    // 填充基本信息
    document.getElementById('modify-dish-id').value = dishData.id || '';
    document.getElementById('modify-dish-name').value = dishData.name || '';
    document.getElementById('modify-dish-price').value = dishData.price || '';
    document.getElementById('modify-dish-image').value = dishData.image || '';
    document.getElementById('modify-dish-description').value = dishData.description || '';
    document.getElementById('modify-dish-status').value = dishData.status || '1';
    
    // 加载分类选项并设置当前分类
    await loadCategoryOptions(dishData.categoryId);
    
    // 填充口味信息
    const flavorsContainer = document.getElementById('modify-dish-flavors');
    flavorsContainer.innerHTML = '';
    
    if (dishData.flavors && dishData.flavors.length > 0) {
      dishData.flavors.forEach(flavor => {
        addFlavorConfigItem(flavor.name, flavor.value);
      });
    }
    
    // 显示弹窗
    document.getElementById('dish-modify-modal').style.display = 'flex';
  }

  // 加载分类选项
  async function loadCategoryOptions(selectedCategoryId = null) {
    try {
      // 调用后端API获取所有分类
      const response = await API.get('/admin/category/list', { type: 1 }); // type: 1 表示菜品分类
      const categorySelect = document.getElementById('modify-dish-category');
      
      // 清空现有选项
      categorySelect.innerHTML = '<option value="">请选择分类</option>';
      
      if (response && response.data) {
        response.data.forEach(category => {
          const option = document.createElement('option');
          option.value = category.id;
          option.textContent = category.name;
          if (selectedCategoryId && category.id == selectedCategoryId) {
            option.selected = true;
          }
          categorySelect.appendChild(option);
        });
      }
    } catch (error) {
      console.error('加载分类选项失败:', error);
      alert('加载分类选项失败，请稍后重试');
    }
  }

  // 关闭菜品修改弹窗
  window.closeDishModifyModal = function() {
    document.getElementById('dish-modify-modal').style.display = 'none';
  };

  // 添加口味配置项
  window.addFlavorConfig = function() {
    addFlavorConfigItem('', '[]');
  };

  function addFlavorConfigItem(name = '', value = '[]') {
    const flavorsContainer = document.getElementById('modify-dish-flavors');
    const flavorIndex = flavorsContainer.children.length;
    
    // 解析value值，如果是JSON字符串则解析，否则使用默认值
    let optionsArray = [];
    try {
      optionsArray = JSON.parse(value);
    } catch (e) {
      optionsArray = [];
    }
    const optionsStr = optionsArray.join(',');
    
    const flavorItem = document.createElement('div');
    flavorItem.className = 'flavor-config-item';
    flavorItem.innerHTML = `
      <input type="text" placeholder="口味名称" value="${escapeHtml(name)}" required>
      <input type="text" placeholder="选项(用逗号分隔)" value="${escapeHtml(optionsStr)}" required>
      <button type="button" class="btn-remove-flavor" onclick="removeFlavorConfig(this)">删除</button>
    `;
    
    flavorsContainer.appendChild(flavorItem);
  }

  // 删除口味配置项
  window.removeFlavorConfig = function(button) {
    button.parentElement.remove();
  };

  // 菜品修改表单提交
  document.getElementById('dish-modify-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    try {
      // 收集基本信息
      const formData = new FormData(e.target);
      const dishData = {
        id: parseInt(formData.get('id')),
        name: formData.get('name'),
        categoryId: parseInt(formData.get('categoryId')),
        price: parseFloat(formData.get('price')),
        image: formData.get('image'),
        description: formData.get('description'),
        status: parseInt(formData.get('status')),
        flavors: []
      };
      
      // 收集口味信息
      const flavorsContainer = document.getElementById('modify-dish-flavors');
      const flavorItems = flavorsContainer.querySelectorAll('.flavor-config-item');
      
      flavorItems.forEach((item) => {
        // 直接查找该项中的输入框，不依赖name属性的索引
        const nameInput = item.querySelector('input[placeholder="口味名称"]');
        const optionsInput = item.querySelector('input[placeholder="选项(用逗号分隔)"]');
        
        if (nameInput && optionsInput && nameInput.value.trim() && optionsInput.value.trim()) {
          // 将逗号分隔的选项转换为JSON数组
          const optionsArray = optionsInput.value.split(',').map(opt => opt.trim()).filter(opt => opt);
          
          dishData.flavors.push({
            name: nameInput.value.trim(),
            value: JSON.stringify(optionsArray)
          });
        }
      });
      
      // 调用后端更新接口
      const response = await API.put('/admin/dish', dishData);
      
      if (response.code === 1) {
        alert('菜品修改成功！');
        closeDishModifyModal();
        // 刷新菜品列表
        const currentParams = getCurrentDishParams();
        await loadDish(currentParams);
      } else {
        alert('菜品修改失败：' + (response.msg || '未知错误'));
      }
      
    } catch (error) {
      console.error('菜品修改失败:', error);
      alert('菜品修改失败，请稍后重试');
    }
  });

  // 获取当前菜品查询参数
  function getCurrentDishParams() {
    const form = document.getElementById('dish-form');
    const formData = new FormData(form);
    return Object.fromEntries(formData.entries());
  }

  // 套餐分页
  $('#setmeal-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const params = Object.fromEntries(new FormData(e.target).entries());
    await loadSetmeal(params);
  });
  async function loadSetmeal(params = { page: 1, pageSize: 10 }) {
    const res = await API.get('/admin/setmeal/page', params);
    renderPagedTable('#setmeal-table', res, params, (p) => loadSetmeal({ ...params, page: p }));
  }

  // 订单搜索
  $('#order-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const params = Object.fromEntries(new FormData(e.target).entries());
    await loadOrders(params);
  });
  async function loadOrders(params = { page: 1, pageSize: 10 }) {
    const res = await API.get('/admin/order/conditionSearch', params);
    renderPagedTable('#order-table', res, params, (p) => loadOrders({ ...params, page: p }));
  }
  $('#btn-order-stats').addEventListener('click', async () => {
    const res = await API.get('/admin/order/statistics');
    $('#order-result').textContent = JSON.stringify(res, null, 2);
  });

  // 报表
  $('#report-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const params = Object.fromEntries(new FormData(e.target).entries());
    const t = await API.get('/admin/report/turnoverStatistics', params);
    const u = await API.get('/admin/report/userStatistics', params);
    const o = await API.get('/admin/report/ordersStatistics', params);
    const top = await API.get('/admin/report/top10', params);
    // 绘制营业额折线图（div）
    try {
      const tv = t?.data || t || {};
      const labels = String(tv.dateList || '').split(',').filter(Boolean);
      const values = String(tv.turnoverList || '')
        .split(',')
        .filter(s => s.length)
        .map(s => parseFloat(s));
      renderLineChart('turnover-chart', labels, values);
    } catch (err) {
      const container = document.getElementById('turnover-chart');
      if (container) container.textContent = '图表渲染失败：' + err;
    }
    
    // 绘制用户统计图表
    try {
      const uv = u?.data || u || {};
      const userLabels = String(uv.dateList || '').split(',').filter(Boolean);
      const newUserValues = String(uv.newUserList || '')
        .split(',')
        .filter(s => s.length)
        .map(s => parseFloat(s));
      const totalUserValues = String(uv.totalUserList || '')
        .split(',')
        .filter(s => s.length)
        .map(s => parseFloat(s));
      renderUserChart('user-chart', userLabels, newUserValues, totalUserValues);
    } catch (err) {
      const container = document.getElementById('user-chart');
      if (container) container.textContent = '用户统计图表渲染失败：' + err;
    }
    
    // 绘制订单统计图表
    try {
      const ov = o?.data || o || {};
      const orderLabels = String(ov.dateList || '').split(',').filter(Boolean);
      const validOrderValues = String(ov.validOrderCountList || '')
        .split(',')
        .filter(s => s.length)
        .map(s => parseFloat(s));
      const totalOrderValues = String(ov.totalOrderCountList || '')
        .split(',')
        .filter(s => s.length)
        .map(s => parseFloat(s));
      renderOrderChart('orders-chart', orderLabels, validOrderValues, totalOrderValues);
    } catch (err) {
      const container = document.getElementById('orders-chart');
      if (container) container.textContent = '订单统计图表渲染失败：' + err;
    }
    
    // 绘制销量TOP10图表
    try {
      const topv = top?.data || top || {};
      const dishNames = String(topv.nameList || '').split(',').filter(Boolean);
      const salesValues = String(topv.numberList || '')
        .split(',')
        .filter(s => s.length)
        .map(s => parseFloat(s));
      renderTop10Chart('top10-chart', dishNames, salesValues);
    } catch (err) {
      const container = document.getElementById('top10-chart');
      if (container) container.textContent = '销量TOP10图表渲染失败：' + err;
    }
  });
  $('#btn-export').addEventListener('click', async () => {
    // 通过携带token的请求获取excel并触发下载
    const headers = API.headers();
    try {
      const res = await fetch('/admin/report/export', { method: 'GET', headers });
      if (!res.ok) {
        const msg = res.status === 401 ? '未登录或令牌失效，请重新登录' : ('导出失败：HTTP ' + res.status);
        alert(msg);
        return;
      }
      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = '运营数据报表.xlsx';
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
    } catch (err) {
      alert('导出失败：' + err);
    }
  });

  // 上传
  $('#upload-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const file = $('#upload-file').files[0];
    const res = await API.upload('/admin/common/upload', file);
    $('#upload-result').textContent = JSON.stringify(res, null, 2);
  });

  // 退出登录
  $('#logout-btn').addEventListener('click', () => {
    if (confirm('确定要退出登录吗？')) {
      // 清除本地存储的token
      localStorage.removeItem('sky_admin_token');
      
      // 更新认证状态
      updateAuthStatus();
      
      // 隐藏主界面，显示登录页面
      const loginPage = document.getElementById('login-page');
      const headerEl = document.querySelector('header');
      const mainEl = document.querySelector('main');
      const asideEl = document.querySelector('aside.sidebar');
      
      loginPage.classList.remove('hidden');
      headerEl.classList.add('hidden');
      mainEl.classList.add('hidden');
      asideEl && asideEl.classList.add('hidden');
      
      // 清空登录表单
      const loginForm = document.getElementById('login-form');
      if (loginForm) {
        loginForm.reset();
      }
      
      // 清空登录结果显示
      const loginResult = document.getElementById('login-result');
      if (loginResult) {
        loginResult.textContent = '';
      }
      
      // 提示用户已退出
      alert('已成功退出登录');
    }
  });
});

function renderPagedTable(selector, res, params, onPageChange) {
  const el = document.querySelector(selector);
  if (!el) return;
  if (!res) { el.textContent = '无数据'; return; }
  const data = res.data || res;
  const records = data.records || [];
  const total = data.total || records.length;
  const page = Number(params.page || 1);
  const pageSize = Number(params.pageSize || 10);
  const pages = Math.max(1, Math.ceil(total / pageSize));
  if (!records.length) { el.textContent = '暂无记录'; return; }
  const keys = Object.keys(records[0]);
  
  // 判断是否为菜品表格（通过selector判断）
  const isDishTable = selector === '#dish-table';
  
  // 判断是否为订单表格（通过selector判断）
  const isOrderTable = selector === '#order-table';
  
  // 判断是否为套餐表格（通过selector判断）
  const isSetmealTable = selector === '#setmeal-table';
  
  // 定义需要隐藏的字段
  // 订单管理界面只显示：订单号(number)、订单状态(status)、用户名(userName)、用户手机(phone)、用户地址(address)、支付方式(payMethod)
  const hiddenFields = ['id', 'updateTime', 'createUser', 'updateUser', 'createTime', 'image', 'description', 'flavors', 'idNumber', 'sex', 'sort', 'checkoutTime', 'payStatus', 'remark', 'consignee', 'cancelReason', 'rejectionReason', 'cancelTime', 'estimatedDeliveryTime', 'deliveryTime', 'packAmount', 'tablewareNumber', 'tablewareStatus', 'categoryId', 'type', 'orderTime', 'amount', 'userId', 'addressBookId', 'deliveryStatus', 'orderDishes', 'orderDetailList'];
  
  // 过滤掉隐藏字段
  const visibleKeys = keys.filter(key => !hiddenFields.includes(key));
  
  // 定义字段显示名称映射
  const fieldNameMap = {
    'name': isDishTable ? '菜品名称' : (isSetmealTable ? '套餐名称' : '名称'),
    'categoryId': '分类',
    'price': '价格',
    'image': '图片',
    'description': '描述',
    'status': '状态',
    'flavors': '口味配置',
    'createTime': '创建时间',
    'updateTime': '更新时间',
    'createUser': '创建人',
    'updateUser': '更新人',
    'username': '用户名',
    'phone': '手机号',
    'sex': '性别',
    'idNumber': '身份证号',
    'type': '类型',
    'sort': '排序',
    'number': '订单号',
    'orderTime': '下单时间',
    'checkoutTime': '结账时间',
    'payMethod': '支付方式',
    'payStatus': '支付状态',
    'amount': '金额',
    'remark': '备注',
    'userName': '用户',
    'phone': '手机号',
    'address': '地址',
    'consignee': '收货人',
    'cancelReason': '取消原因',
    'rejectionReason': '拒单原因',
    'cancelTime': '取消时间',
    'estimatedDeliveryTime': '预计送达时间',
    'deliveryTime': '送达时间',
    'packAmount': '打包费',
    'tablewareNumber': '餐具数量',
    'tablewareStatus': '餐具状态'
  };
  
  // 构建表头，如果是菜品表格或套餐表格则添加操作列
  const thead = '<thead><tr>' + visibleKeys.map(k => `<th>${fieldNameMap[k] || k}</th>`).join('') + 
                (isDishTable || isSetmealTable ? '<th>操作</th>' : '') + '</tr></thead>';
  
  // 判断是否为图片URL的函数
  function isImageUrl(key, value) {
    // 检查字段名是否包含image或者值是否为图片URL
    return (key.toLowerCase().includes('image') || 
            (typeof value === 'string' && 
             (value.includes('aliyuncs.com') || 
              value.match(/\.(jpg|jpeg|png|gif|webp)$/i))));
  }
  
  // 创建图片单元格内容
  function createImageCell(imageUrl) {
    if (!imageUrl || imageUrl === 'null' || imageUrl === '') {
      return '<span class="no-image">暂无图片</span>';
    }
    
    const imgId = 'img_' + Math.random().toString(36).substr(2, 9);
    return `<img id="${imgId}" src="${imageUrl}" alt="图片" class="table-image" 
                 onerror="this.style.display='none'; this.nextElementSibling.style.display='inline';" 
                 onload="this.style.display='inline';">
            <span class="no-image" style="display:none;">暂无图片</span>`;
  }
  
  // 判断是否为categoryId字段
  function isCategoryIdField(key) {
    return key.toLowerCase() === 'categoryid';
  }
  
  // 创建分类单元格内容
  async function createCategoryCell(categoryId) {
    if (!categoryId) {
      return '<span class="no-category">未分类</span>';
    }
    
    try {
      // 调用后端API根据ID查询分类名称
      const response = await API.get(`/admin/category/${categoryId}`);
      if (response && response.data) {
        return `<span class="category-name">${response.data}</span>`;
      } else {
        return '<span class="no-category">未知分类</span>';
      }
    } catch (error) {
      console.error('获取分类名称失败:', error);
      return '<span class="no-category">获取失败</span>';
    }
  }
  
  // 判断是否为status字段
  function isStatusField(key) {
    return key.toLowerCase() === 'status';
  }
  
  // 创建状态单元格内容
  function createStatusCell(statusValue) {
    const statusText = statusValue === 1 ? '启用' : '禁用';
    const statusClass = statusValue === 1 ? 'status-enabled' : 'status-disabled';
    return `<span class="${statusClass}">${statusText}</span>`;
  }
  
  // 订单状态映射函数
  function getOrderStatusText(status) {
    const statusMap = {
      1: '待付款',
      2: '待接单', 
      3: '已接单',
      4: '派送中',
      5: '已完成',
      6: '已取消'
    };
    return statusMap[status] || '未知状态';
  }
  
  // 获取订单状态对应的CSS类名
  function getOrderStatusClass(status) {
    const statusClassMap = {
      1: 'order-status-pending-payment',
      2: 'order-status-to-be-confirmed',
      3: 'order-status-confirmed', 
      4: 'order-status-delivery',
      5: 'order-status-completed',
      6: 'order-status-cancelled'
    };
    return statusClassMap[status] || 'order-status-unknown';
  }
  
  // 判断是否为订单状态字段
  function isOrderStatusField(key) {
    return key.toLowerCase() === 'status';
  }
  
  // 创建订单状态单元格内容
  function createOrderStatusCell(statusValue) {
    const statusText = getOrderStatusText(statusValue);
    const statusClass = getOrderStatusClass(statusValue);
    return `<span class="${statusClass}">${statusText}</span>`;
  }
  
  // 判断是否为flavors字段
  function isFlavorsField(key) {
    return key.toLowerCase() === 'flavors';
  }
  
  // 创建flavors单元格内容
  function createFlavorsCell(flavorsData) {
    if (!flavorsData || flavorsData.length === 0) {
      return '<span class="no-flavors">无口味选项</span>';
    }
    
    try {
      let flavorsHtml = '<div class="flavors-container">';
      flavorsData.forEach(flavor => {
        if (flavor.name && flavor.value) {
          // 解析value字段中的JSON数组
          let options = [];
          try {
            options = JSON.parse(flavor.value);
          } catch (e) {
            // 如果解析失败，直接使用原值
            options = [flavor.value];
          }
          
          flavorsHtml += `<div class="flavor-item">
                           <span class="flavor-name">${escapeHtml(flavor.name)}:</span>
                           <span class="flavor-options">${options.map(opt => `<span class="flavor-option">${escapeHtml(opt)}</span>`).join('')}</span>
                         </div>`;
        }
      });
      flavorsHtml += '</div>';
      return flavorsHtml;
    } catch (e) {
      return '<span class="no-flavors">口味数据格式错误</span>';
    }
  }
  
  // 由于需要异步处理分类名称，需要重构表格生成逻辑
  const createTableBody = async () => {
    const rows = [];
    for (const r of records) {
      const cells = [];
      for (const k of visibleKeys) {
        const value = r[k];
        if (isImageUrl(k, value)) {
          cells.push(`<td class="image-cell">${createImageCell(value)}</td>`);
        } else if (isFlavorsField(k)) {
          cells.push(`<td class="flavors-cell">${createFlavorsCell(value)}</td>`);
        } else if (isStatusField(k) && isDishTable) {
          // 菜品状态处理
          cells.push(`<td class="status-cell">${createStatusCell(value)}</td>`);
        } else if (isOrderStatusField(k) && isOrderTable) {
          // 订单状态处理
          cells.push(`<td class="order-status-cell">${createOrderStatusCell(value)}</td>`);
        } else if (isCategoryIdField(k)) {
          const categoryCell = await createCategoryCell(value);
          cells.push(`<td class="category-cell">${categoryCell}</td>`);
        } else {
          cells.push(`<td>${escapeHtml(value)}</td>`);
        }
      }
      
      // 如果是菜品表格，添加操作按钮
      if (isDishTable) {
        cells.push(`<td class="action-cell">
          <button class="btn-modify" data-dish-id="${r.id}" onclick="modifyDish(${r.id})">修改</button>
        </td>`);
      }
      
      // 如果是套餐表格，添加操作按钮
      if (isSetmealTable) {
        cells.push(`<td class="action-cell">
          <button class="btn-modify" data-setmeal-id="${r.id}" onclick="modifySetmeal(${r.id})">修改</button>
        </td>`);
      }
      
      rows.push(`<tr>${cells.join('')}</tr>`);
    }
    return `<tbody>${rows.join('')}</tbody>`;
  };

  // 异步生成表格内容
  createTableBody().then(tbody => {
    // 分页按钮
    const makeBtn = (p, text = p, active = false) => `<button class="page-btn ${active?'active':''}" data-page="${p}">${text}</button>`;
    let nums = '';
    const start = Math.max(1, page - 3);
    const end = Math.min(pages, start + 6);
    for (let p = start; p <= end; p++) nums += makeBtn(p, p, p === page);
    const pagHtml = `
      <div class="pagination">
        ${makeBtn(Math.max(1, page-1), '«')}
        ${nums}
        ${makeBtn(Math.min(pages, page+1), '»')}
        <span class="page-jump">到第 <input type="number" min="1" max="${pages}" value="${page}" class="page-input"> 页 <button class="page-go">跳转</button></span>
      </div>`;

    el.innerHTML = `<div class="total">共 ${total} 条</div>${pagHtml}<table>${thead}${tbody}</table>${pagHtml}`;

    // 事件绑定（委托）
    el.querySelectorAll('.page-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        const target = Number(btn.dataset.page);
        if (onPageChange) onPageChange(target);
      });
    });
    el.querySelectorAll('.page-go').forEach(go => {
      go.addEventListener('click', () => {
        const input = go.parentElement.querySelector('.page-input');
        let target = Number(input.value);
        if (Number.isNaN(target)) target = page;
        target = Math.max(1, Math.min(pages, target));
        if (onPageChange) onPageChange(target);
      });
    });
  }).catch(error => {
    console.error('生成表格失败:', error);
    el.innerHTML = '<div class="error">表格生成失败，请重试</div>';
  });
}

function escapeHtml(val) {
  if (val === null || val === undefined) return '';
  return String(val)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

// 套餐管理相关功能
document.addEventListener('DOMContentLoaded', () => {
  // 新增套餐按钮事件
  const btnAddSetmeal = document.getElementById('btn-add-setmeal');
  if (btnAddSetmeal) {
    btnAddSetmeal.addEventListener('click', showAddSetmealModal);
  }

  // 新增套餐表单提交事件
  const addSetmealForm = document.getElementById('add-setmeal-form');
  if (addSetmealForm) {
    addSetmealForm.addEventListener('submit', handleAddSetmealSubmit);
  }

  // 新增套餐对话框取消按钮
  const addSetmealCancel = document.getElementById('add-setmeal-modal-cancel');
  if (addSetmealCancel) {
    addSetmealCancel.addEventListener('click', () => {
      document.getElementById('add-setmeal-modal').classList.add('hidden');
    });
  }

  // 修改套餐表单提交事件
  const modifySetmealForm = document.getElementById('modify-setmeal-form');
  if (modifySetmealForm) {
    modifySetmealForm.addEventListener('submit', handleModifySetmealSubmit);
  }

  // 修改套餐对话框取消按钮
  const modifySetmealCancel = document.getElementById('modify-setmeal-modal-cancel');
  if (modifySetmealCancel) {
    modifySetmealCancel.addEventListener('click', () => {
      document.getElementById('modify-setmeal-modal').classList.add('hidden');
    });
  }
});

// 显示新增套餐对话框
async function showAddSetmealModal() {
  try {
    // 加载分类选项
    await loadCategoryOptionsForSetmeal('add-setmeal-categoryId');
    
    // 清空表单
    document.getElementById('add-setmeal-form').reset();
    
    // 重置套餐菜品容器
    const dishesContainer = document.getElementById('add-setmeal-dishes');
    dishesContainer.innerHTML = '<button type="button" id="btn-add-dish-to-setmeal">添加菜品</button>';
    
    // 绑定新增套餐添加菜品按钮事件
    const addDishBtn = document.getElementById('btn-add-dish-to-setmeal');
    if (addDishBtn) {
      addDishBtn.addEventListener('click', () => {
        addDishToSetmealContainer('add-setmeal-dishes');
      });
    }
    
    // 显示对话框
    document.getElementById('add-setmeal-modal').classList.remove('hidden');
  } catch (error) {
    console.error('显示新增套餐对话框失败:', error);
    alert('加载分类信息失败，请重试');
  }
}

// 显示修改套餐对话框
async function showModifySetmealModal(setmealData) {
  try {
    // 加载分类选项
    await loadCategoryOptionsForSetmeal('modify-setmeal-categoryId');
    
    // 填充表单数据
    document.getElementById('modify-setmeal-id').value = setmealData.id;
    document.getElementById('modify-setmeal-name').value = setmealData.name || '';
    document.getElementById('modify-setmeal-categoryId').value = setmealData.categoryId || '';
    document.getElementById('modify-setmeal-price').value = setmealData.price || '';
    document.getElementById('modify-setmeal-status').value = setmealData.status || '1';
    document.getElementById('modify-setmeal-description').value = setmealData.description || '';
    document.getElementById('modify-setmeal-image').value = setmealData.image || '';
    
    // 重置套餐菜品容器
    const dishesContainer = document.getElementById('modify-setmeal-dishes');
    dishesContainer.innerHTML = '<button type="button" id="btn-modify-add-dish-to-setmeal">添加菜品</button>';
    
    // 绑定修改套餐添加菜品按钮事件
    const modifyAddDishBtn = document.getElementById('btn-modify-add-dish-to-setmeal');
    if (modifyAddDishBtn) {
      modifyAddDishBtn.addEventListener('click', () => {
        addDishToSetmealContainer('modify-setmeal-dishes');
      });
    }
    
    // 加载套餐菜品信息
    if (setmealData.setmealDishes && setmealData.setmealDishes.length > 0) {
      setmealData.setmealDishes.forEach(dish => {
        addDishToSetmealContainer('modify-setmeal-dishes', dish);
      });
    }
    
    // 显示对话框
    document.getElementById('modify-setmeal-modal').classList.remove('hidden');
  } catch (error) {
    console.error('显示修改套餐对话框失败:', error);
    alert('加载套餐信息失败，请重试');
  }
}

// 加载分类选项
async function loadCategoryOptionsForSetmeal(selectId) {
  try {
    const response = await API.get('/admin/category/list', { type: 2 }); // type=2表示套餐分类
    const categories = response.data || [];
    
    const select = document.getElementById(selectId);
    select.innerHTML = '<option value="">请选择分类</option>';
    
    categories.forEach(category => {
      const option = document.createElement('option');
      option.value = category.id;
      option.textContent = category.name;
      select.appendChild(option);
    });
  } catch (error) {
    console.error('加载分类选项失败:', error);
    throw error;
  }
}

// 处理新增套餐表单提交
async function handleAddSetmealSubmit(event) {
  event.preventDefault();
  
  try {
    const formData = new FormData(event.target);
    const setmealData = Object.fromEntries(formData.entries());
    
    // 收集套餐菜品信息
    const setmealDishes = collectSetmealDishes('add-setmeal-dishes');
    setmealData.setmealDishes = setmealDishes;
    
    // 数据类型转换
    setmealData.price = parseFloat(setmealData.price);
    setmealData.status = parseInt(setmealData.status);
    setmealData.categoryId = parseInt(setmealData.categoryId);
    
    const response = await API.send('POST', '/admin/setmeal', setmealData);
    
    if (response.code === 1) {
      alert('新增套餐成功');
      document.getElementById('add-setmeal-modal').classList.add('hidden');
      // 刷新套餐列表
      const params = getCurrentSetmealParams();
      await loadSetmeal(params);
    } else {
      alert('新增套餐失败：' + (response.msg || '未知错误'));
    }
  } catch (error) {
    console.error('新增套餐失败:', error);
    alert('新增套餐失败，请重试');
  }
}

// 处理修改套餐表单提交
async function handleModifySetmealSubmit(event) {
  event.preventDefault();
  
  try {
    const formData = new FormData(event.target);
    const setmealData = Object.fromEntries(formData.entries());
    
    // 收集套餐菜品信息
    const setmealDishes = collectSetmealDishes('modify-setmeal-dishes');
    setmealData.setmealDishes = setmealDishes;
    
    // 数据类型转换
    setmealData.id = parseInt(setmealData.id);
    setmealData.price = parseFloat(setmealData.price);
    setmealData.status = parseInt(setmealData.status);
    setmealData.categoryId = parseInt(setmealData.categoryId);
    
    const response = await API.put('/admin/setmeal', setmealData);
    
    if (response.code === 1) {
      alert('修改套餐成功');
      document.getElementById('modify-setmeal-modal').classList.add('hidden');
      // 刷新套餐列表
      const params = getCurrentSetmealParams();
      await loadSetmeal(params);
    } else {
      alert('修改套餐失败：' + (response.msg || '未知错误'));
    }
  } catch (error) {
    console.error('修改套餐失败:', error);
    alert('修改套餐失败，请重试');
  }
}

// 获取当前套餐查询参数
function getCurrentSetmealParams() {
  const form = document.getElementById('setmeal-form');
  const formData = new FormData(form);
  return Object.fromEntries(formData.entries());
}

// 收集套餐菜品信息
function collectSetmealDishes(containerId) {
  const container = document.getElementById(containerId);
  const dishItems = container.querySelectorAll('.setmeal-dish-item');
  const setmealDishes = [];
  
  dishItems.forEach(item => {
    const dishId = item.querySelector('[name="dishId"]').value;
    const copies = item.querySelector('[name="copies"]').value;
    const dishSelect = item.querySelector('[name="dishId"]');
    
    if (dishId && copies && dishSelect) {
      // 获取选中菜品的名称和价格
      const selectedOption = dishSelect.options[dishSelect.selectedIndex];
      const name = selectedOption ? selectedOption.text : '';
      const price = selectedOption ? selectedOption.dataset.price : 0;
      
      setmealDishes.push({
        dishId: parseInt(dishId),
        copies: parseInt(copies),
        name: name,
        price: parseFloat(price) || 0
      });
    }
  });
  
  return setmealDishes;
}

// 添加菜品到套餐容器
function addDishToSetmealContainer(containerId, dishData = {}) {
  const container = document.getElementById(containerId);
  const dishItem = document.createElement('div');
  dishItem.className = 'setmeal-dish-item';
  dishItem.innerHTML = `
    <div class="dish-item-row">
      <select name="dishId" required>
        <option value="">请选择菜品</option>
      </select>
      <input name="copies" type="number" min="1" placeholder="份数" value="${dishData.copies || 1}" required>
      <button type="button" class="remove-dish-btn">删除</button>
    </div>
  `;
  
  // 在添加按钮前插入
  const addButton = container.querySelector('button');
  container.insertBefore(dishItem, addButton);
  
  // 加载菜品选项
  loadDishOptions(dishItem.querySelector('select'), dishData.dishId);
  
  // 绑定删除事件
  dishItem.querySelector('.remove-dish-btn').addEventListener('click', () => {
    dishItem.remove();
  });
}

// 加载菜品选项
async function loadDishOptions(selectElement, selectedDishId = null) {
  try {
    const response = await API.get('/admin/dish/list');
    const dishes = response.data || [];
    
    selectElement.innerHTML = '<option value="">请选择菜品</option>';
    dishes.forEach(dish => {
      const option = document.createElement('option');
      option.value = dish.id;
      option.textContent = dish.name;
      option.dataset.price = dish.price; // 添加价格数据
      if (selectedDishId && dish.id === selectedDishId) {
        option.selected = true;
      }
      selectElement.appendChild(option);
    });
  } catch (error) {
    console.error('加载菜品选项失败:', error);
  }
}

// 修改套餐函数
async function modifySetmeal(setmealId) {
  try {
    // 获取套餐详细信息
    const res = await API.get(`/admin/setmeal/${setmealId}`);
    if (res.code === 1 && res.data) {
      await showModifySetmealModal(res.data);
    } else {
      alert('获取套餐信息失败');
    }
  } catch (error) {
    console.error('获取套餐信息失败:', error);
    alert('获取套餐信息失败');
  }
}